package com.zgl.gemduel.service;

import com.zgl.gemduel.model.RoomResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class RoomResourceNotificationService {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    /**
     * 同步房间资源给房间内的所有客户端
     * @param roomId 房间ID
     * @param roomResource 房间资源
     */
    public void notifyRoomResourceUpdate(String roomId, RoomResource roomResource) {
        if (roomResource != null) {
            // 创建符合前端期望格式的消息
            Map<String, Object> message = new HashMap<>();
            message.put("type", "room_resource_update");
            message.put("payload", roomResource);
            
            // 发送房间资源更新消息给房间内的所有客户端
            messagingTemplate.convertAndSend("/topic/room/" + roomId, message);
        }
    }

    /**
     * 同步指令给房间内的所有客户端
     * @param roomId 房间ID
     * @param Command 指令
     */
    public void notifyRoomCommand(String roomId, String Command) {
        if (Command != null) {
            // 创建符合前端期望格式的消息
            Map<String, Object> message = new HashMap<>();
            message.put("type", "room_command");
            message.put("payload", Command);

            // 发送房间资源更新消息给房间内的所有客户端
            messagingTemplate.convertAndSend("/topic/room/" + roomId, message);
        }
    }

    /**
     * 同步房间资源给指定客户端
     * @param sessionId 客户端会话ID
     * @param roomId 房间ID
     * @param roomResource 房间资源
     */
    public void notifyRoomResourceUpdateToUser(String sessionId, String roomId, RoomResource roomResource) {
        if (roomResource != null) {
            // 创建符合前端期望格式的消息
            Map<String, Object> message = new HashMap<>();
            message.put("type", "room_resource_update");
            message.put("payload", roomResource);
            
            // 发送房间资源更新消息给指定客户端
            messagingTemplate.convertAndSendToUser(sessionId, "/topic/room_resource_update", message);
        }
    }
}